package com.example.p2p;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.NetworkInfo;
import android.net.wifi.p2p.WifiP2pConfig;
import android.net.wifi.p2p.WifiP2pDevice;
import android.net.wifi.p2p.WifiP2pDeviceList;
import android.net.wifi.p2p.WifiP2pManager;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;

import com.example.im.R;
import com.example.util.BaseActivity;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.ServerSocket;
import java.net.Socket;

import androidx.appcompat.app.AppCompatActivity;

// 服务端代码
public class ServerActivity extends BaseActivity {
    private WifiP2pManager wifiP2pManager;
    private WifiP2pManager.Channel channel;
    private BroadcastReceiver receiver;
    private ServerSocket serverSocket;
    private Thread acceptThread;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // 初始化 WifiP2pManager
        wifiP2pManager = (WifiP2pManager) getSystemService(Context.WIFI_P2P_SERVICE);
        if (wifiP2pManager == null) {
            Toast.makeText(this, "该设备不支持 Wi-Fi Direct", Toast.LENGTH_SHORT).show();
            return;
        }

        // 初始化 Channel
        channel = wifiP2pManager.initialize(this, getMainLooper(), null);

        // 注册广播接收器
        receiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                String action = intent.getAction();
                if (WifiP2pManager.WIFI_P2P_STATE_CHANGED_ACTION.equals(action)) {
                    // Wi-Fi Direct 状态发生变化
                    int state = intent.getIntExtra(WifiP2pManager.EXTRA_WIFI_STATE, -1);
                    if (state == WifiP2pManager.WIFI_P2P_STATE_ENABLED) {
                        Log.d("Server", "Wi-Fi Direct 已启用");
                    } else {
                        Log.d("Server", "Wi-Fi Direct 已停用");
                    }

                } else if (WifiP2pManager.WIFI_P2P_PEERS_CHANGED_ACTION.equals(action)) {
                    // 设备列表发生变化
                    wifiP2pManager.requestPeers(channel, new WifiP2pManager.PeerListListener() {
                        @Override
                        public void onPeersAvailable(WifiP2pDeviceList peers) {
                            for (WifiP2pDevice device : peers.getDeviceList()) {
                                Log.d("Server", "发现设备：" + device.deviceName + ", " + device.deviceAddress);

                                // 开始连接设备
                                if (device.deviceName.equals("client")) {
                                    WifiP2pConfig config = new WifiP2pConfig();
                                    config.deviceAddress = device.deviceAddress;
                                    wifiP2pManager.connect(channel, config, new WifiP2pManager.ActionListener() {
                                        @Override
                                        public void onSuccess() {
                                            Log.d("Server", "连接设备成功");
                                        }

                                        @Override
                                        public void onFailure(int reason) {
                                            Log.d("Server", "连接设备失败：" + reason);
                                        }
                                    });
                                }
                            }
                        }
                    });

                } else if (WifiP2pManager.WIFI_P2P_CONNECTION_CHANGED_ACTION.equals(action)) {
                    // 连接状态发生变化
                    NetworkInfo networkInfo = intent.getParcelableExtra(WifiP2pManager.EXTRA_NETWORK_INFO);
                    if (networkInfo.isConnected()) {
                        // 建立连接
                        Log.d("Server", "连接已建立");

                        // 创建服务器 Socket
                        try {
                            serverSocket = new ServerSocket(8888);
                            Log.d("Server", "服务器 Socket 已创建");
                        } catch (IOException e) {
                            e.printStackTrace();
                        }

                        // 开启接收线程监听客户端连接
                        acceptThread = new Thread(new Runnable() {
                            @Override
                            public void run() {
                                while (true) {
                                    try {
                                        // 等待客户端连接
                                        final Socket socket = serverSocket.accept();
                                        Log.d("Server", "客户端已连接：" + socket.getInetAddress());

                                        // 读取客户端发送的数据
                                        BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                                        String data = reader.readLine();

                                        // 发送响应给客户端
                                        BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
                                        writer.write("服务端收到了数据[" + data + "]");
                                        writer.newLine();
                                        writer.flush();
                                    } catch (IOException e) {
                                        e.printStackTrace();
                                    }
                                }
                            }
                        });
                        acceptThread.start();

                    } else {
                        // 断开连接
                        Log.d("Server", "连接已断开");
                        if (serverSocket != null) {
                            try {
                                serverSocket.close();
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                        }
                        if (acceptThread != null) {
                            acceptThread.interrupt();
                        }
                    }

                } else if (WifiP2pManager.WIFI_P2P_THIS_DEVICE_CHANGED_ACTION.equals(action)) {
                    // 本设备信息发生变化
                    WifiP2pDevice device = intent.getParcelableExtra(WifiP2pManager.EXTRA_WIFI_P2P_DEVICE);
                    Log.d("Server", "本设备信息发生变化：" + device.deviceName + ", " + device.deviceAddress);
                }
            }
        };
        IntentFilter filter = new IntentFilter();
        filter.addAction(WifiP2pManager.WIFI_P2P_STATE_CHANGED_ACTION);
        filter.addAction(WifiP2pManager.WIFI_P2P_PEERS_CHANGED_ACTION);
        filter.addAction(WifiP2pManager.WIFI_P2P_CONNECTION_CHANGED_ACTION);
        filter.addAction(WifiP2pManager.WIFI_P2P_THIS_DEVICE_CHANGED_ACTION);
        registerReceiver(receiver, filter);

        // 发现并连接设备
        wifiP2pManager.discoverPeers(channel, new WifiP2pManager.ActionListener() {
            @Override
            public void onSuccess() {
                Log.d("Server", "开始查找设备");
            }

            @Override
            public void onFailure(int reason) {
                Log.d("Server", "查找设备失败：" + reason);
            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        // 关闭服务端 Socket
        if (serverSocket != null) {
            try {
                serverSocket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        // 停止监听线程
        if (acceptThread != null) {
            acceptThread.interrupt();
        }

        // 注销广播接收器
        unregisterReceiver(receiver);
    }
}

